package com.maxtech.common;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.maxtech.common.gps.GpsTask;
import com.maxtech.common.gps.GpsTaskCallBack;
import com.maxtech.common.gps.LogUtil;
import com.maxtech.common.gps.GpsTask.GpsData;
import com.maxtech.common.gps.IAddressTask.MLocation;
import com.maxtech.common.gps.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class GpsActivity extends Activity implements OnClickListener {

	private static final long GPS_TIMEOUT = 5 * 60 *1000;
	protected static final String TAG = "GpsActivity";
	private TextView gps_tip = null;
	private AlertDialog dialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		gps_tip = (TextView) findViewById(R.id.gps_tip);
		findViewById(R.id.do_gps).setOnClickListener(GpsActivity.this);
		findViewById(R.id.do_apn).setOnClickListener(GpsActivity.this);
		findViewById(R.id.do_wifi).setOnClickListener(GpsActivity.this);
//
		dialog = new ProgressDialog(GpsActivity.this);
		dialog.setTitle("请稍等...");
		dialog.setMessage("正在定位...");
		
		
//		findViewById(R.id.do_gps).setOnClickListener(new Button.OnClickListener(){
//			@Override
//			public void onClick(View v) {
//				final String address = "苏州市星湖街328号";
//				getLatLonByAddress(address);
//			}			
//		});
	}

	protected void getLatLonByAddress(String address) {
		getLatLonByAddress(address, new onDataReady() {			
			@Override
			public void setData(Object ob) {
				try {
					if(ob==null)
						return;
					String str = (String)ob;
					LogUtil.e(TAG, str);
					
					JSONObject tmp = new JSONObject(str);
					JSONArray jo = tmp.getJSONArray("results");
					LogUtil.e(TAG, jo.toString());
					tmp = jo.getJSONObject(0);
					tmp = tmp.getJSONObject("geometry");
					tmp = tmp.getJSONObject("location");

					String lat = tmp.getString("lat");
					String lon = tmp.getString("lng");
					
					double d_lat = tmp.getDouble("lat");
					double d_lon = tmp.getDouble("lng");

					int i1 = (int)(d_lat * 1000000);
					int i2 = (int)(d_lon * 1000000);
					
					ptToSet = new GeoPoint(i1, i2);
					
					Utils.log("lat:"+ d_lat + ",lon:"+ d_lon);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}						
			}
		});
	}

	public GeoPoint ptToSet;
	public static GeoPoint getFromLocalName(double d1, double d2){
		try{
			int i1 = (int)(d1 * 1000000);
			int i2 = (int)(d2 * 1000000);

			GeoPoint geopoint = new GeoPoint(i1, i2);
			return geopoint;
		} catch(Exception e){
			LogUtil.ex(TAG, "", e);
			return null;
		}		
	}
	public interface onDataReady {
		public void setData(Object ob);
	}
	
	public void getLatLonByAddress(final String address,final onDataReady dataReady) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					dataReady.setData(msg.obj);
					return;
				}
				LogUtil.e(TAG, "null");
			}
		};
		new Thread() {
			@Override
			public void run() {
				try {
					String tmpurl = Utils.url.replace("{0}", address);
					handler.sendMessage(Message.obtain(handler, 0, Utils.getContent(tmpurl)));
					return;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					handler.sendMessage(Message.obtain(handler, 1, null));
					e.printStackTrace();
					return;
				}
			}
		}.start();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onClick(View v) {
		gps_tip.setText("");
		switch (v.getId()) {
		case R.id.do_apn:
			do_apn();
			break;
		case R.id.do_gps:

			GpsTask gpstask = new GpsTask(GpsActivity.this,
					new GpsTaskCallBack() {

						@Override
						public void gpsConnectedTimeOut() {
							gps_tip.setText("获取GPS超时了");
						}

						@Override
						public void gpsConnected(GpsData gpsdata) {
							do_gps(gpsdata);

							String result = "getLatLonByGPS"+"location.getLatitude():" + gpsdata.getLatitude() 
									+ ",location.getLongitude():" + gpsdata.getLongitude();
//							
							Log.e(TAG, result);
							Utils.Toast(GpsActivity.this, result);	
						}

					}, GPS_TIMEOUT);
			gpstask.execute();
			break;
		case R.id.do_wifi:
			do_wifi();
			break;
		}
	}

	private void do_apn() {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				MLocation location = null;
				try {
					location = new AddressTask(GpsActivity.this,
							AddressTask.DO_APN).doApnPost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(location == null)
					return null;
				return location.toString();
			}

			@Override
			protected void onPreExecute() {
				dialog.show();
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(String result) {
				if(result == null){
					gps_tip.setText("基站定位失败了...");					
				}else {
					gps_tip.setText(result);
				}
				dialog.dismiss();
				super.onPostExecute(result);
			}
			
		}.execute();
	}

	private void do_gps(final GpsData gpsdata) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				MLocation location = null;
				try {
					Log.i("do_gpspost", "经纬度：" + gpsdata.getLatitude() + "----" + gpsdata.getLongitude());
					location = new AddressTask(GpsActivity.this,
							AddressTask.DO_GPS).doGpsPost(gpsdata.getLatitude(),
									gpsdata.getLongitude());
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(location == null)
					return "GPS信息获取错误";
				return location.toString();
			}

			@Override
			protected void onPreExecute() {
				dialog.show();
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(String result) {
				gps_tip.setText(result);
				dialog.dismiss();
				super.onPostExecute(result);
			}
			
		}.execute();
	}

	private void do_wifi() {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				MLocation location = null;
				try {
					location = new AddressTask(GpsActivity.this,
							AddressTask.DO_WIFI).doWifiPost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(location == null)
					return null;
				return location.toString();
			}

			@Override
			protected void onPreExecute() {
				dialog.show();
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(String result) {
				if(result != null){
					gps_tip.setText(result);
				}else {
					gps_tip.setText("WIFI定位失败了...");
				}
				
				dialog.dismiss();
				super.onPostExecute(result);
			}
			
		}.execute();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		
		android.os.Process.killProcess(android.os.Process.myPid());
	}	
}